﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Channels;
using TrackSystem.Contracts;
using TrackSystem.Entities.DataShaping;
using TrackSystem.Entities.Dtos.Channel;
using TrackSystem.Entities.Dtos.Sensor;
using TrackSystem.Entities.Models;
using TrackSystem.Entities.RequestFeatures;

namespace TrackSystem.API.Controllers
{
    /// <summary>
    /// 传感器控制器
    /// </summary>
    [ApiController]
    [Route("api/sensor")]
    public class SensorDefController : ControllerBase
    {
        private readonly IRepositoryWrapper wrapper;
        private readonly ILogger<SensorDefController> logger;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="wrapper"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public SensorDefController(
            IRepositoryWrapper wrapper,
            ILogger<SensorDefController> logger,
            IMapper mapper)
        {
            this.wrapper = wrapper;
            this.logger = logger;
            this.mapper = mapper;
        }
        
        /// <summary>
        /// 获取所有的成员
        /// </summary>
        /// <returns></returns>
        [HttpGet("all")]
        public async Task<IActionResult> GetAllSensors()
        {
            try
            {
                //var sensors =  wrapper.Sensor.GetAll().Include(a => a.Channel);
                var sensors = await wrapper.Sensor.GetAllListAsync();
                var result = mapper.Map<IEnumerable<SensorDto>>(sensors);
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[传感器设置] 获取异常");
                return StatusCode(StatusCodes.Status500InternalServerError, "[传感器设置] 获取异常");
            }
        }

        /// <summary>
        /// 获取包含通信通道及设备细节的所有传感器
        /// </summary>
        /// <returns></returns>
        [HttpGet("all/detail")]
        public async Task<IActionResult> GetAllSensorsWithChannel()
        {
            try
            {
                var sensors = await wrapper.Sensor.GetAllWithChannelAsync();
                var result = mapper.Map<IEnumerable<SensorWithChannelDto>>(sensors);

                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[传感器设置] 获取异常");
                return StatusCode(StatusCodes.Status500InternalServerError, "[传感器设置] 获取异常");
            }
        }

        /// <summary>
        /// 获取单个传感器信息，包含通信通道及设备细节
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id:int}/detail")]
        public async Task<ApiResult<SensorWithChannelDto>> GetSingleSensorWithChannel(int id)
        {
            try
            {
                return await wrapper.Sensor.GetSingleWithChannelAsync(id);

            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[传感器设置] 获取异常");
                return ApiResult<SensorWithChannelDto>.Fail("[传感器设置] 获取异常", StatusCodes.Status500InternalServerError);
            }
        }

        /// <summary>
        /// 获取分页传感器信息
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpGet("paged")]
        public async Task<IActionResult> GetPaged([FromQuery] RequestParameter parameter)
        {
            try
            {
                var result = await Task.Run(() => wrapper.Sensor.GetPagedSensors(parameter)) ;
                Response.Headers.Append("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(result.MetaData));
                var chns = mapper.Map<IEnumerable<SensorTable>>(result).ShapeData(parameter.Fields);

                return Ok(chns);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[通道设置] 获取异常");
                return StatusCode(StatusCodes.Status500InternalServerError, "[通道设置] 获取异常");
            }
        }

        /// <summary>
        /// 添加传感器
        /// </summary>
        /// <param name="sensor"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult<SensorWithChannelDto>> AddSensor(SensorForCreatedDto sensor)
        {
            if (sensor == null)
            {
                return ApiResult<SensorWithChannelDto>.Fail("传感器信息不能为空", StatusCodes.Status204NoContent);
            }

            var ensorTable = mapper.Map<SensorTable>(sensor);
            var result = await wrapper.Sensor.AddSensorAsync(ensorTable);
            if (result.Success)
            {
                // 添加传感器后，更新相关的寄存器
                var varResult =  await wrapper.Var.UpdateBaseSensor(ensorTable);
                if (varResult.Success) 
                    return ApiResult<SensorWithChannelDto>.Ok(mapper.Map<SensorWithChannelDto>(ensorTable), "传感器添加成功");
                else 
                    return ApiResult<SensorWithChannelDto>.Fail(varResult.Message ??= "", varResult.Code);
            }
            return result;
        }

        /// <summary>
        /// 修改传感器信息
        /// </summary>
        /// <param name="sensor"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<SensorWithChannelDto>> UpdateSensor(SensorForUpdateDto sensor)
        {
            if (sensor == null)
            {
                return ApiResult<SensorWithChannelDto>.Fail("传感器信息不能为空", StatusCodes.Status204NoContent);
            }
            var ensorTable = mapper.Map<SensorTable>(sensor);
            var result =  await wrapper.Sensor.UpdateSensorAsync(ensorTable);
            if (result.Success)
            {
                // 添加传感器后，更新相关的寄存器
                var varResult = await wrapper.Var.UpdateBaseSensor(ensorTable);
                if (varResult.Success)
                    return ApiResult<SensorWithChannelDto>.Ok(mapper.Map<SensorWithChannelDto>(ensorTable), "传感器添加成功");
                else
                    return ApiResult<SensorWithChannelDto>.Fail(varResult.Message ??= "", varResult.Code);
            }
            return result;
        }

        /// <summary>
        /// 删除传感器信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id:int}")]
        public async Task<ApiResult<SensorWithChannelDto>> DeleteSensor(int id)
        {
            var result =  await wrapper.Sensor.DeleteSensorAsync(id);
            if (!result.Success) return result;
            var snrResult = await wrapper.Var.DeleteBaseSensor(id);
            return snrResult.Success ?
                ApiResult<SensorWithChannelDto>.Ok(result.Data ??= new SensorWithChannelDto(), result.Message ??= "") : 
                ApiResult<SensorWithChannelDto>.Fail(snrResult.Message ??= "");
        }
    }
}
